package com.jzxk.tool;

import org.apache.commons.lang.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;

/**
 * @author 今朝惜客
 * @CreateTime : 16/9/13 下午5:23
 * @Description : XXX
 */
public class HttpInvoker {

	public static String httpsPost(String postUrl, Map<String, String> postHeaders, String postEntity, String charset) throws IOException {

		if (StringUtils.isEmpty(charset)) {
			charset = "utf-8";
		}

		URL postURL = new URL(postUrl);
		HttpsURLConnection httpURLConnection = (HttpsURLConnection) postURL.openConnection();
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setDoInput(true);
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setUseCaches(false);
		httpURLConnection.setInstanceFollowRedirects(true);
		httpURLConnection.setRequestProperty("Content-Type ", "application/x-www-form-urlencoded");

		if (postHeaders != null) {
			for (String pKey : postHeaders.keySet()) {
				httpURLConnection.setRequestProperty(pKey, postHeaders.get(pKey));
			}
		}
		if (postEntity != null) {
			DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
			out.write(postEntity.getBytes(charset));
			out.flush();
			out.close(); // flush and close
		}
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), charset));
		StringBuilder sbStr = new StringBuilder();
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			sbStr.append(line);
		}
		bufferedReader.close();
		httpURLConnection.disconnect();
		return new String(sbStr.toString().getBytes(), charset);
	}
}
